<template>
  <el-dialog width="500px" title="员工导入" :visible="showExcelDialog" @close="$emit('update:showExcelDialog',false)">
    <el-row type="flex" justify="center">
      <div class="upload-excel">
        <!-- 监听文件改变 -->
        <input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="uploadChange">
        <div class="drop">
          <i class="el-icon-upload" />
          <!-- 下载员工模板 -->
          <el-button type="text" @click="getTemplate">下载导入模板</el-button>
          <!-- 点击上传方法 -->
          <span>将文件拖到此处或<el-button type="text" @click="handleUpload">点击上传</el-button></span>
        </div>
      </div>
      <!-- 取消按钮 -->
    </el-row>
    <el-row type="flex" justify="end">
      <!-- update:props属性名，值 直接修改 .sync修饰符的属性值 -->
      <el-button size="mini" type="primary" @click="$emit('update:showExcelDialog', false)">取消</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import { getExportTemplate, uploadExcel } from '@/api/employee'
import FileSaver from 'file-saver'
export default {
  props: {
    showExcelDialog: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    // 下载员工模板
    async getTemplate() {
      const result = await getExportTemplate()
      FileSaver.saveAs(result, '员工导入模板.xlsx')
    },
    // 弹出文件选择框
    handleUpload() {
      this.$refs['excel-upload-input'].click() // $refs.属性名与$refs[属性名]等价
    },
    // 上传文件并关闭弹层
    async uploadChange(event) {
      // console.log(event.target.files)
      const files = event.target.files // input的文件列表
      if (files.length > 0) {
        // 大于0 说明没有文件要上传
        const data = new FormData()
        // file: file类型
        data.append('file', files[0]) // 将文件参数加入到formData中
        try {
          // 调用上传接口 参数为file-data类型
          await uploadExcel(data)
          // 成功
          this.$emit('uploadSuccess') // 通知父组件 上传成功
          this.$emit('update:showExcelDialog', false) // 关闭弹层
        // eslint-disable-next-line no-empty
        } catch (error) {
        } finally {
          // 不论成功或者失败都会执行finally
          // 清空文件选择器的内容 下次点击上传一个新的excel文件
          this.$refs['excel-upload-input'].value = ''
        }
      }
    }
  }
}
</script>
<style scoped lang="scss">
.upload-excel{
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px;
  width: 360px;
  height: 180px;
  color: #697086;
  .excel-upload-input{
    display: none;
    z-index: -9999;
  }
  .btn-upload, .drop{
    border: 1px dashed #dcdfe6;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    text-align: center;
    flex-direction: column;
    line-height: 160px;
    border-radius: 8px;
  }
  .drop{
    line-height: 40px;
    color: #bbb;
    i {
      font-size: 60px;
      display: block;
      color:#c0c4cc;
    }
  }
}
</style>
